package com.navidove.appspotlight.model.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.navidove.appspotlight.model.bo.AppAdItem;
import com.navidove.appspotlight.model.bo.SysImage;
import com.navidove.appspotlight.model.dao.AppAdItemDao;
import com.navidove.appspotlight.model.service.AppAdService;
import com.navidove.appspotlight.model.service.SysImageService;

@Service
public class AppAdServiceImpl implements AppAdService {

	@Autowired
	private SysImageService sysImageService;
	
	@Autowired
	private AppAdItemDao appAdItemDao;
	
	public AppAdItem getAppAdItem(Long id) {
		return appAdItemDao.get(id);
	}
	
	public AppAdItem getAppAdItem(String appName) {
		return appAdItemDao.get(Restrictions.eq("appName", appName).ignoreCase());
	}
	
	public void saveAppAdItem(AppAdItem appAdItem, MultipartFile imageFile) {
		Date now = new Date();
		
		SysImage sysImage = sysImageService.saveSysImage(imageFile);
		
		if (appAdItem.getId() == null) {
			appAdItem.setCrtAt(now);
		}
		
		if (sysImage != null) {
			appAdItem.setSysImage(sysImage);
		}
		appAdItem.setUpdAt(now);
		
		DetachedCriteria criteria = DetachedCriteria.forClass(AppAdItem.class);
		criteria.setProjection(Projections.max("adSeq"));
		Number seq =  (Number) appAdItemDao.getByCriteria(criteria);
		if (seq == null) {
			appAdItem.setAdSeq(1);
		} else {
			appAdItem.setAdSeq(seq.intValue()+1);
		}
		
		appAdItemDao.save(appAdItem);
	}
	
	@SuppressWarnings("unchecked")
	public List<AppAdItem> getAppAdItemList(Boolean enable, String adType) {
		DetachedCriteria criteria = DetachedCriteria.forClass(AppAdItem.class);
		if (enable != null) {
			criteria.add(Restrictions.eq("enable", enable));
		}
		if (StringUtils.isNotBlank(adType)) {
			criteria.add(Restrictions.eq("adType", adType));
		}
		criteria.addOrder(Order.asc("adType"));
		criteria.addOrder(Order.asc("adSeq"));
		return (List<AppAdItem>) appAdItemDao.getListByCriteria(criteria);
	}

	public void deleteAppAdItem(Long id) {
		appAdItemDao.delete(appAdItemDao.get(id));
	}
	
	public void sort(Long[] ids) {
		for (int i = 0; i < ids.length; i++) {
			AppAdItem item = appAdItemDao.get(ids[i]);
			item.setAdSeq(i+1);
			appAdItemDao.save(item);
		}
	}
}
